import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { Good } from './goods.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Raw, In } from 'typeorm';
import { cryptoString } from '../libs/lib';
import * as generator from 'generate-password';
import { CreateGoodDto } from './dto/create-good.dto';
import { RemoveGoodDto } from './dto/remote-good.dto';
import { FindGoodDto } from './dto/find-good.dto';

@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(Good)
    private goodsRepository: Repository<Good>,
  ) {}

  async create(createGoodDto: CreateGoodDto): Promise<any> {
    const { name, des, price, createdAt, updatedAt } = createGoodDto;

    createGoodDto.createdAt = createdAt || new Date();
    createGoodDto.updatedAt = new Date();

    const isExist = await this.goodsRepository.count({
      where: {
        name,
      },
    });
    if (isExist > 0) {
      return {
        statusCode: 202,
        message: '商品已存在',
      };
    }

    return await this.goodsRepository.save(createGoodDto);
  }

  delete(removeGoodDto: RemoveGoodDto): any {
    const { ids } = removeGoodDto;
    return this.goodsRepository.delete(ids);
  }

  // 更新
  async update(updateGoodData): Promise<any> {
    const { id, updateGoodDto } = updateGoodData;
    updateGoodDto.updatedAt = new Date();
    const { name } = updateGoodDto;

    const isExist = await this.goodsRepository.count({
      where: {
        name,
      },
    });
    if (isExist > 1) {
      return {
        statusCode: 201,
        message: '已存在',
      };
    }

    return await this.goodsRepository.update(id, updateGoodDto);
  }

  //查询所有
  async findAll(query: any): Promise<any> {
    const { keyword, page = 1, limit = 10, beginTime, endTime } = query;
    const skip = (page - 1) * limit;

    let params = {
      skip,
      take: limit,
    };

    let whereParams = {};

    if (keyword) {
      whereParams = Object.assign(whereParams, {
        name: Like(`%${keyword}%`),
      });
    }

    params = Object.assign(
      {
        select: ['id', 'name', 'des', 'price', 'updatedAt'],
      },
      params,
      {
        where: whereParams,
      },
      {
        order: {
          updatedAt: 'DESC',
        },
      },
    );

    const [data, total] = await this.goodsRepository.findAndCount(params);

    return {
      total,
      data,
    };
  }
}
